﻿/**
* jQuery EasyUI 1.3.4
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact author: info@jeasyui.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
* jQuery EasyUI gridselector Extensions 1.0 beta
* jQuery EasyUI gridselector 组件扩展
* jeasyui.extensions.gridselector.js
* 二次开发 李溪林
* 最近更新：2014-02-11
*
* 依赖项：
*   1、jquery.jdirk.js v1.0 beta late
*   2、jeasyui.extensions.js v1.0 beta late
*   3、jeasyui.extensions.menu.js v1.0 beta late
*   4、jeasyui.extensions.panel.js v1.0 beta late
*   5、jeasyui.extensions.window.js v1.0 beta late
*   6、jeasyui.extensions.dialog.js v1.0 beta late
*
* Copyright (c) 2013 ChenJianwei personal All rights reserved.
* http://www.chenjianwei.org
*/
(function ($, undefined) {

    //window的默认options
    var _windowDefaults = {
        title: "选择数据",
        iconCls: "icon-hamburg-zoom",
        width: 700,
        height: 410,
        closable: true,
        shadow: true,
        modal: true,
        resizable: true,
        draggable: true,
        maximizable: true,
        minimizable: false,
        collapsible: true
    };

    //window的options解析
    var _getSelectorWindowOptions = function (options) {
        var windowOptions = {};
        for (var key in options) {
            if (key == "title" || key == "iconCls" || key == "width" || key == "height" || key == "resizable" || key == "collapsible" || key == "draggable") {
                windowOptions[key] = options[key];
            }
        }
        windowOptions = $.extend({}, $.fn.window.defaults, _windowDefaults, windowOptions);
        return windowOptions;
    };

    //datagrid的options解析
    var _getDataGridOptions = function (options) {
        return $.extend({}, $.fn.datagrid.defaults, options, {
            noheader: true,
            fit: true,
            border: false,
            striped: true,
            fitColumns: true,
            rownumbers: true,
            checkOnSelect: true,
            remoteSort: false
        });
    };

    //treegrid的options解析
    var _getTreeGridOptions = function (options) {
        return $.extend({}, $.fn.treegrid.defaults, options, {
            noheader: true,
            fit: true,
            border: false,
            striped: true,
            fitColumns: true,
            rownumbers: true,
            checkOnSelect: true,
            remoteSort: false
        });
    };

    //自定义属性的解析
    var _getCustomOptions = function (options) {
        var customOptions = {
            onBeforeClose: function () { },
            onEnterClick: function () { },
            onCancelClick: function () { },
            selected: null
        };
        for (var key in options) {
            if (key == "onBeforeClose" || key == "onEnterClick" || key == "onCancelClick" || key == "selected") {
                customOptions[key] = options[key];
            }
        }
        return customOptions;
    };









    /********************************
    Tree和两个DataGrid的选择器，west位置是tree，datagrid1为待选择，datagrid2为已选择
    OnEnterClick的参数为：selections
    options格式参见comlib.js
    *********************************/
    $.easyui.showTreeDblGridSelector = function (options) {
        var windowOptions = _getSelectorWindowOptions(options);
        var treeOptions = {
            animate: true,
            lines: true,
            onLoadSuccess: function (node) {
                //if (node == null) {
                //    $(this).tree("expandAll");
                //}
            }
        };
        var datagrid1Options = $.extend(_getDataGridOptions(options), {
            noheader: false,
            title: "待选择项",
            iconCls: null,
            toolbar: null
        });
        var datagrid2Options = $.extend(_getDataGridOptions(options), {
            url: null,
            noheader: false,
            title: "已选择项",
            iconCls: null,
            toolbar: null,
            pagination: false
        });

        var customOptions = $.extend(_getCustomOptions(options), {
            treeWidth: options.treeWidth ? options.treeWidth : 170,
            treeUrl: options.treeUrl,
            treeQueryParamOnSelect: options.treeQueryParamOnSelect,
            centerWidth: 60,
            toolbar: options.toolbar,
            fireOnClick: options.fireOnClick,
            selectedUrl: options.selectedUrl
        });

        var windowId = "selector_" + $.util.guid("N");
        var treeId = "tree_" + $.util.guid("N");
        var datagrid1Id = "datagrid1_" + $.util.guid("N");
        var datagrid2Id = "datagrid2_" + $.util.guid("N");

        var selectorWindow = $("<div />").attr("id", windowId);
        var content = $("<div />").addClass("easyui-layout").attr("data-options", "fit: true");

        //south位置的确定、取消按钮
        var layoutSouth = $("<div />").attr("data-options", "region:'south',border:false").css({
            "text-align": "right",
            "padding": "5px",
            "border-top": "1px solid #8DB2E3",
            "background-color": "#E0ECFF"
        });
        var btnEnter = $("<a />").addClass("easyui-linkbutton").text("确定").attr({
            "data-options": "iconCls: 'icon-ok', disabled: true",
            "href": "javascript:void(0);"
        });
        var btnCancel = $("<a />").addClass("easyui-linkbutton").text("取消").attr({
            "data-options": "iconCls: 'icon-cancel', disabled: true",
            "href": "javascript:void(0);"
        }).css("margin-left", "10px");
        $(layoutSouth).append(btnEnter).append(btnCancel);

        //west位置的tree
        var layoutWest = $("<div />").attr({
            "data-options": "region:'west',border: false"
        }).css({ "width": customOptions.treeWidth + "px", "border-right-width": "1px" });
        var tree = $("<ul />").attr("id", treeId);
        $(layoutWest).append(tree);


        //center位置的子layout
        var layoutCenter = $("<div />").attr("data-options", "region:'center',border: false");
        var insideLayout = $("<div />").addClass("easyui-layout").attr("data-options", "fit: true");

        var gridWidth = (windowOptions.width - customOptions.treeWidth - customOptions.centerWidth) / 2;
        var insideWest = $("<div />").attr({
            "data-options": "region:'west',border: false"
        }).css({ "width": (gridWidth + 60) + "px" });
        //     子layout west位置的datagrid1
        var datagrid1 = $("<table />").attr("id", datagrid1Id);
        $(insideWest).append(datagrid1);

        var insideCenter = $("<div />").attr({
            "data-options": "region:'center',border: false"
        }).css({
            "text-align": "center",
            "padding-top": "" + customOptions.centerWidth + "px",
            "border-left-width": "1px",
            "border-right-width": "1px",
            "background-color": "#efefef"
        });
        //     子layout center位置的按钮
        var br1 = $("<br />");
        var br2 = $("<br />");
        var br3 = $("<br />");
        var btn1 = $("<a />").addClass("easyui-linkbutton").attr("data-options", "iconCls: 'icon-pagination-last', plain: true").attr("title", "选择全部");
        //var btn2 = $("<a />").addClass("easyui-linkbutton").attr("data-options", "iconCls: 'icon-pagination-next', plain: true").attr("title", "选择勾选部分");
        //var btn3 = $("<a />").addClass("easyui-linkbutton").attr("data-options", "iconCls: 'icon-pagination-prev', plain: true").attr("title", "取消勾选部分");
        var btn4 = $("<a />").addClass("easyui-linkbutton").attr("data-options", "iconCls: 'icon-pagination-first', plain: true").attr("title", "取消全部");
        $(insideCenter).append(btn1).append(br1).append(br3).append(btn4);

        var insideEast = $("<div />").attr({
            "data-options": "region:'east',border: false"
        }).css({ "width": (gridWidth - 60) + "px" });
        //     子layout east位置的datagrid2
        var datagrid2 = $("<table />").attr("id", datagrid2Id);
        $(insideEast).append(datagrid2);

        $(insideLayout).append(insideWest).append(insideCenter).append(insideEast);
        $(layoutCenter).append(insideLayout);
        $(content).append(layoutWest).append(layoutCenter).append(layoutSouth);

        //选择事件、取消事件
        var _select = function (rowData) {
            if (rowData && !$.util.isEmptyObjectOrNull(rowData)) {
                var opts = datagrid1.datagrid("options");
                var idField = datagrid2.datagrid("options").idField;
                var idValue = ($.util.isEmptyObjectOrNull(idField) ? rowData : rowData[idField]);
                var exists = datagrid2.datagrid("getRowIndex", idValue) > -1;
                if (!exists) {
                    if (opts.singleSelect) {
                        while (datagrid2.datagrid("getRows").length > 0) {
                            _unselect(datagrid2.datagrid("getRows")[0]);
                        }
                        datagrid2.datagrid("unselectAll");
                    }
                    datagrid2.datagrid("appendRow", rowData);
                }
            }
        };
        var _unselect = function (rowData) {
            if (rowData && !$.util.isEmptyObjectOrNull(rowData)) {
                var idField = datagrid2.datagrid("options").idField;
                var idValue = ($.util.isEmptyObjectOrNull(idField) ? rowData : rowData[idField]);
                var index = datagrid2.datagrid("getRowIndex", idValue);
                if (index > -1) {
                    datagrid2.datagrid("deleteRow", index);
                }
            }
        };
        var _unselect1 = function (rowData) {
            if (rowData && !$.util.isEmptyObjectOrNull(rowData)) {
                var idField = datagrid2.datagrid("options").idField;
                var idValue = ($.util.isEmptyObjectOrNull(idField) ? rowData : rowData[idField]);
                var index = datagrid2.datagrid("getRowIndex", idValue);
                if (index > -1) {
                    var index1 = datagrid1.datagrid("getRowIndex", idValue);
                    if (index1 > -1) {
                        datagrid1.datagrid("unselectRow", index1);
                    }
                    else { datagrid2.datagrid("deleteRow", index); }
                }
            }
        };

        //组件初始化
        if (!$.string.isNullOrWhiteSpace(customOptions.treeUrl))
        { $.extend(treeOptions, { url: customOptions.treeUrl }); }
        if ($.isFunction(options.onBeforeSelect))
        { $.extend(treeOptions, { onBeforeSelect: options.onBeforeSelect }); }
        $.extend(treeOptions, {
            width: customOptions.treeWidth,
            dataPlain: options.dataPlain,
            parentField: options.parentField,
            onSelect: function (node) {
                var param = {};
                if ($.isFunction(customOptions.treeQueryParamOnSelect)) { param = customOptions.treeQueryParamOnSelect.call(this, node); }
                $(datagrid1).datagrid("load", param);
            }
        });
        $(tree).tree(treeOptions);

        if (customOptions.fireOnClick) {
            $.extend(datagrid1Options, {
                onSelect: function (rowIndex, rowData) {
                    _select(rowData);
                },
                onUnselect: function (rowIndex, rowData) {
                    _unselect(rowData);
                }
            });
        }
        else {
            $.extend(datagrid1Options, {
                onDblClickRow: function (rowIndex, rowData) {
                    _select(rowData);
                }
            });
        }

        var toolbar = null;
        if (!$.util.isEmptyObjectOrNull(customOptions.toolbar)) {
            toolbar = $(customOptions.toolbar).css({
                "padding-left": "10px",
                "background-color": "#efefef"
            });
        }

        $.extend(datagrid1Options, {
            toolbar: toolbar,
            onLoadSuccess: function (data) {
                $.fn.datagrid.extensions.onLoadSuccess.apply(this, arguments);//调用扩展的事件防止覆盖
                if (datagrid1Options.pagination) { $(this).datagrid("getPager").pagination({ displayMsg: "" }); }

                $(btnEnter).linkbutton("enable");
                $(btnCancel).linkbutton("enable");
                $(selectorWindow).prev().find(".panel-tool a").removeAttr("disabled");

                var selected = datagrid2.datagrid("getRows");
                if (selected && selected.length) {
                    var opts = $(this).datagrid("options");
                    var idField = opts.idField;
                    selected.forEach(function (val) {
                        var row = $(datagrid1).datagrid("findRow", val[idField]);
                        if (row) {
                            $(datagrid1).datagrid("selectRecord", val[idField]);
                        }
                    });
                }

            }
        });
        $(datagrid1).datagrid(datagrid1Options);

        if (customOptions.fireOnClick) {
            $.extend(datagrid2Options, {
                onClickRow: function (rowIndex, rowData) {
                    _unselect1(rowData);
                }
            });
        }
        else {
            $.extend(datagrid2Options, {
                onDblClickRow: function (rowIndex, rowData) {
                    _unselect1(rowData);
                }
            });
        }
        $(datagrid2).datagrid(datagrid2Options);

        //datagrid2的已选数据加载
        if (!$.string.isNullOrWhiteSpace(customOptions.selectedUrl) && (!$.string.isNullOrWhiteSpace(customOptions.selected) || !$.util.isEmptyObjectOrNull(customOptions.selected))) {
            var strSelected = "";
            if ($.type(customOptions.selected) == "string")
            { strSelected = customOptions.selected; }
            else if ($.type(customOptions.selected) == "array")
            { strSelected = customOptions.selecteds.join(","); }
            if (!$.string.isNullOrWhiteSpace(strSelected)) {
                $.post(customOptions.selectedUrl, { selected: strSelected }, function (data) {
                    $(datagrid2).datagrid("loadData", data);
                });
            }
        }

        //按钮事件 选择全部、取消全部
        $(btn1).click(function () {
            var selections = $(datagrid1).datagrid("getRows");
            if ($.type(selections) == "array") {
                for (var i = 0; i < selections.length; i++) {
                    _select(selections[i]);
                }
            }
            $(datagrid1).datagrid("selectAll");
        });
        $(btn4).click(function () {
            datagrid2.datagrid("clearSelections");
            datagrid2.datagrid("loadData", []);
            datagrid1.datagrid("clearSelections");
        })

        var _onOpen = windowOptions.onOpen;
        var _onBeforeClose = windowOptions.onBeforeClose;
        var _onClose = windowOptions.onClose;
        $.extend(windowOptions, {
            content: content,
            onOpen: function () {
                $(this).prev().find(".panel-tool a").attr("disabled", true);
                _onOpen.call(this);
            },
            onClose: function () {
                _onClose.apply(this, arguments);
                $(this).window("destroy");
            }
        });

        $(selectorWindow).window(windowOptions);

        //确定、关闭按钮
        $(btnEnter).click(function () {
            if ($(this).linkbutton("options").disabled == true) { return; }
            var selections = $(datagrid2).datagrid("getRows");
            if ($.isFunction(customOptions.onEnterClick)) {
                if (customOptions.onEnterClick(selections) == false) {
                    return;
                }
            }
            $(selectorWindow).window("close");
        });
        $(btnCancel).click(function () {
            if ($(this).linkbutton("options").disabled == true) { return; }
            $(selectorWindow).window("close");
        });

        $(selectorWindow).window("open");


        return { selectorWindow: selectorWindow, tree: tree, datagrid1: datagrid1, datagrid2: datagrid2, toolbar: toolbar };
    };

})(jQuery);